﻿layui.use(['table', 'dropdown', 'layer', 'form'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var layer = layui.layer;
    var form = layui.form;
    var laypage = layui.laypage;
    window.Show = function Show() {
        var token = localStorage.getItem("token")
        var model = JSON.stringify({
            saleReturnsNo: $("#saleReturnsNo").val(),
            salesOrdersNo: $("#salesOrdersNo").val(),
            productName: $("#productName").val(),
            orderStatus: parseInt($("#orderStatus").val()) || 0,
            productNo: "",
            clientNo: "",
            clientName:""
        })

        $.ajax({
            url: '../Purchase/SaleReturnShow',
            type: 'post',
            //contentType: 'application/json',
            data: { model: model, token: token },
            success: function (res) {
                res = JSON.parse(res);
                // 处理数据并渲染表格
                var cols = [
                    [
                        { field: 'saleReturnsId', type: 'checkbox', fixed: 'left' },
                        { field: 'saleReturnsNo', title: '退货单号', width: 80 },
                        { field: 'productName', title: '产品名称', width: 120 },
                        { field: 'productNo', title: '产品编号', width: 120 },
                        { field: 'productSpec', title: '产品规格', width: 120 },
                        { field: 'unitName', title: '单位', width: 120 },
                        { field: 'price', title: '单价', width: 120 },
                        { field: 'saleReturnsNum', title: '退货数', width: 120 },
                        { field: 'saleReturnsTotal', title: '总额', width: 120 },
                        { field: 'salesOrdersNo', title: '销售单号', width: 120 },
                        { field: 'clientName', title: '客户名称', width: 120 },
                        { field: 'saleReturnsState', title: '状态', width: 120 },
                        {
                            fixed: 'right', title: '操作', width: 150, templet: function (d) {
                                return '<a href="#" class="layui - btn layui - btn - xs layui - btn - primary" onclick="viewFunction(' + d.saleReturnsId + ')">查看</a>' +
                                    '<a href="#" class="layui - btn layui - btn - xs layui - btn - primary" onclick="editFunction(' + d.saleReturnsId + ')">确认</a>';
                            }
                        }
                    ]
                ];
                table.render({
                    elem: '#test',
                    data: res,
                    cols: cols,
                    page: true,
                    limits: [5, 10, 15, 20],
                    limit: 5,//设置每页显示的条数。
                });
            },
        });
    }
    window.viewFunction = function viewFunction(saleReturnsId) {
        var model = JSON.stringify({
            saleReturnsId: saleReturnsId
        })
        var token = localStorage.getItem("token")
        $.ajax({
            url: '../Purchase/SaleReturnFan',
            data: { model: model, token: token },
            type: 'post',
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                $.each(res, function () {
                    $("#saleReturnsNo1").val(this.saleReturnsNo)
                    $("#salesOrdersNo1").val(this.salesOrdersNo)
                    $("#clientName").val(this.clientName)
                    $("#salesOrdersPerson").val(this.salesOrdersPerson);
                    $("#salesOrdersPhone").val(this.salesOrdersPhone)
                    $("#clientNo").val(this.clientNo);
                    $("#salesOrdersRemark").val(this.salesOrdersRemark)
                    $("#singleMaker").val(this.singleMaker);
                    var datePart = this.singleTime.split('T')[0];
                    $("#singledate").val(datePart);
                    // 设置下拉框默认选择
                    var procurementTypeId = this.procurementTypeId;
                    $("#procurementTypeId").val(procurementTypeId);
                    layui.form.render('select'); // 重新渲染select表单元素
                    // 设置下拉框默认选择
                    var saleReturnsState = this.saleReturnsState;
                    $("#saleReturnsState").val(saleReturnsState);
                    layui.form.render('select'); // 重新渲染select表单元素

                })
                // 再进行表格渲染相关操作
                layui.use('table', function () {
                    var form = layui.form;
                    var table = layui.table;
                    var cols = [[
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'productNo', title: '产品编号' },
                        { field: 'productName', title: '产品名称' },
                        { field: 'productSpec', title: '规格' },
                        { field: 'unitName', title: '单位', edit: 'text', },
                        { field: 'saleReturnsNum', title: '数量', edit: 'text' },
                        { field: 'batch', title: '批次', edit: 'text' },
                        { field: 'saleReturnsNum', title: '退货数', edit: 'text' },
                        { field: 'price', title: '单价' },
                        { field: 'saleReturnsTotal', title: '总额' }
                    ]];
                    table.render({
                        elem: allocationProduct,
                        data: res,
                        cols: cols,
                        page: true,
                        limit: 5,
                        limits: [5, 8, 10]
                    });
                });
            }
        })
        layer.open({
            type: 1, // page 层类型
            area: ['800px', '800px'],
            title: 'Hello layer',
            shade: 0.6, // 遮罩透明度
            shadeClose: true, // 点击遮罩区域，关闭弹层
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<div style="padding: 32px;">
            <form class="layui-form layui-form-pane" action="">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">退货单号：</label>
            <div class="layui-input-block">
                <input type="text" name="saleReturnsNo1" id="saleReturnsNo1" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据类型：</label>
            <div class="layui-input-inline">
                <select id="procurementTypeId" name="procurementTypeId" lay-filter="aihao">
                    <option value="0">全部</option>
                    <option value="实际订单">实际订单</option>
                    <option value="预知订单">预知订单</option>
                    <option value="创建订单">创建订单</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据状态：</label>
            <div class="layui-input-inline">
                 <select id="saleReturnsState" name="saleReturnsState" lay-filter="aihao">
                    <option value="0">全部</option>
                    <option value="实际订单">实际订单</option>
                    <option value="预知订单">预知订单</option>
                    <option value="创建订单">创建订单</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">销售单号：</label>
            <div class="layui-input-block">
                <input type="text" name="salesOrdersNo1" id="salesOrdersNo1" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label"> 制单人：</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期：</label>
            <div class="layui-input-inline">
                <input type="date" name="singledate" id="singledate" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">联系人：</label>
            <div class="layui-input-block">
                <input type="text" name="salesOrdersPerson" id="salesOrdersPerson" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label"> 客户编号：</label>
            <div class="layui-input-inline">
                <input type="text" name="clientNo" id="clientNo" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">客户名称：</label>
            <div class="layui-input-inline">
                <input type="text" name="clientName" id="clientName" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">电话：</label>
            <div class="layui-input-inline">
                <input type="text" name="salesOrdersPhone" id="salesOrdersPhone" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="salesOrdersRemark" id="salesOrdersRemark" autocomplete="off" class="layui-input">
            </div>
        </div>

    </div>
    <div style="float:left;margin-top:40px;margin-bottom:40px">
        <h4>产品信息</h4>
    </div>
    <table class="layui-hide" id="allocationProduct"></table>
    <div class="layui-form-item" style="text-align:center;margin-top:50px">
        <button type="button" class="layui-btn" lay-submit lay-filter="demo2" onclick="location.href='/Purchase/SaleReturn'">确认</button>
        <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Purchase/SaleReturn'">取消</button>
    </div>
</form>
                    </div> `
        });
        form.render()
    }

    $(function () {
        Show()
    })

    window.Output = function Output() {
        var data = [];

        //直接获取表格正文数据并添加到data数组，跳过表头（thead）获取
        $('table.layui-table tbody tr').each(function () {
            var rowData = [];
            $(this).find('td').each(function () {
                rowData.push($(this).text());
            });
            data.push(rowData);
        });

        //将数据转换为Worksheet对象
        var worksheet = XLSX.utils.aoa_to_sheet(data);

        //创建一个新的Workbook对象，并将Worksheet添加进去
        var workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

        //将Workbook对象转换为二进制数据
        var wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });

        //将二进制数据转换为Blob对象
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i < s.length; i++) {
                view[i] = s.charCodeAt(i) & 0xff;
            }
            return new Blob([buf], { type: 'application/octet-stream' });
        }
        var blob = s2ab(wbout);

        //创建一个下载链接并触发点击事件来下载文件
        var url = URL.createObjectURL(blob);
        var link = document.createElement('a');
        link.href = url;
        link.download = '销售退货SaleReturn.xlsx';
        link.click();

        //释放URL对象
        URL.revokeObjectURL(url);
    }

    window.IsdelAll = function IsdelAll() {
        var checkStatus = table.checkStatus('test');
        var checkedData = checkStatus.data;
        var saleReturnsId = [];
        for (var i = 0; i < checkedData.length; i++) {
            saleReturnsId.push(checkedData[i].saleReturnsId);
        }
        if (saleReturnsId == 0) {
            layui.msg("至少选择一条数据", { icon: 2 })
            return;
        }
        var model = JSON.stringify({
            saleReturnsId: saleReturnsId
        });
        console.log(model);
        var token = localStorage.getItem("token")
        layer.confirm("确认删除吗", function () {
            $.ajax({
                url: '../Purchase/SaleReturnIsdelAll',
                data: { model: model, token: token },
                type: 'post',
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res)
                    if (res > 0) {
                        layui.msg("删除成功", {icon:1})
                        Show();
                    }
                    else {
                        layui.msg("删除失败", {icon:2})
                    }
                }
            })
        })
    }
});